package com.zeng.createmd.restfulmodule.util;

import java.io.*;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class SerializableUtil {

    public static <T> T deserialize(File file) {
        return (T) deserialize(file, Map.class);
    }

    public static <T> T deserialize(File file, Class<T> tClass) {
        if (!file.exists()) {
            return null;
        }

        FileInputStream fileInputStream = null;
        ObjectInputStream objectInputStream = null;
        Object o = null;
        try {
            fileInputStream = new FileInputStream(file);
            objectInputStream = new ObjectInputStream(fileInputStream);

            o = objectInputStream.readObject();
            if (o == null) {
                return null;
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        } finally {
            CloseUtil.close(fileInputStream, objectInputStream);
        }

        if (isSupperClass(o.getClass(), tClass)) {
            return (T) o;
        }
        throw new RuntimeException("类型转换异常");
    }

    public static void serialize(File file, Object data) {
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }

        FileOutputStream fileOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            CloseUtil.close(fileOutputStream, objectOutputStream);
        }
    }

    private static boolean isSupperClass(Class c, Class o) {
        if (c.getSuperclass().equals(o)) {
            return true;
        }
        if (c.equals(o)) {
            return true;
        }
        Set<Class> collect = Arrays.stream(c.getInterfaces()).collect(Collectors.toSet());
        return collect.contains(o);
    }

}
